<template>
  <div id="resetButtonBtnId">reset button[从头开始走]</div>
  <div id="cesiumContainer" class="fullSize"></div>
  <div id="loadingOverlay"><h1>Loading...</h1></div>
  <div id="toolbar"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import * as Cesium from 'cesium';
import CesiumNavigation from 'cesium-navigation-es6';

import { CesiumNavigationOptions } from './cesium/initViewer';

import MousePosition from './cesium/MousePosition';
import './Widgets/widgets.css';

// 设置cesium 静态资源路径
window.CESIUM_BASE_URL = '/';
Cesium.Ion.defaultAccessToken =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNDkwYWVhOS0wNzI5LTQ3OTEtOWFiMC1kY2M3MTFiM2I2NWQiLCJpZCI6MTkyNTU1LCJpYXQiOjE3MDY1MTM0MTh9.YAPVHr1d7PBuWayCXM9deCxKg3AbtsXUJiVpubVS3NY';

onMounted(async () => {
  // const viewer = initViewer();
  const viewer = new Cesium.Viewer('cesiumContainer', {
    shouldAnimate: true,
    //信息窗口
    infoBox: false, // 可查看某个建筑的详细信息

    //显示查询按钮
    geocoder: false,
    //home按钮
    homeButton: false,
    // 控制查看器的显示模式-地球/平面
    sceneModePicker: false,
    // 是否显示图层选择
    baseLayerPicker: false,
    //帮助按钮
    navigationHelpButton: false,
    //播放动画
    // animation: false,
    //时间线
    // timeline: false,
    //全屏模式
    fullscreenButton: false,
    //设置地形
    terrainProvider: Cesium.createWorldTerrain({
      requestWaterMask: true, // 水纹效果  海里面有波浪的效果
      requestVertextNormal: true, // 光照效果
    }),
    // 添加谷歌影像图 https://blog.csdn.net/GIS_yuhua/article/details/89765167
    // imageryProvider: new Cesium.UrlTemplateImageryProvider({
    //   // url: '/apiWeixing/vt/lyrs=s&hl=zh-CN&x={x}&y={y}&z={z}&s=Gali',
    //   url: '/apiGugo/maps/vt?lyrs=s@800&x={x}&y={y}&z={z}',
    //   tilingScheme: new Cesium.WebMercatorTilingScheme(),
    //   minimumLevel: 1,
    //   maximumLevel: 30,
    // }),
  });
  // case官网 https://sandcastle.cesium.com/?src=Multi-part%20CZML.html
  const statusDisplay = document.createElement('div');
  const fuelDisplay = document.createElement('div');
  // const czmlPath = './Assets/';
  const czmlPath = '/apiCesium/SampleData/';
  // const czmlPath = 'https://sandcastle.cesium.com/SampleData/MultipartVehicle_part1.czml';
  // const czmlPath = 'https://sandcastle.cesium.com/SampleData/MultipartVehicle_part2.czml';
  // const czmlPath = 'https://sandcastle.cesium.com/SampleData/MultipartVehicle_part3.czml';
  let vehicleEntity;

  // 根据鼠标位置生成经纬度值
  const mousePosition = new MousePosition(viewer);

  //如需自定义罗盘控件，请看下面的自定义罗盘控件
  new CesiumNavigation(viewer, CesiumNavigationOptions);

  // Add a blank CzmlDataSource to hold our multi-part entity/entities.
  const dataSource = new Cesium.CzmlDataSource();
  // console.log('dataSource:', dataSource);
  viewer.dataSources.add(dataSource);

  // This demo shows how a single path can be broken up into several CZML streams.
  const partsToLoad = [
    {
      url: 'MultipartVehicle_part1.czml',
      range: [0, 1500],
      requested: false,
      loaded: false,
    },
    {
      url: 'MultipartVehicle_part2.czml',
      range: [1500, 3000],
      requested: false,
      loaded: false,
    },
    {
      url: 'MultipartVehicle_part3.czml',
      range: [3000, 4500],
      requested: false,
      loaded: false,
    },
  ];

  function updateStatusDisplay() {
    let msg = '';
    partsToLoad.forEach(function (part) {
      msg += `${part.url} - `;
      if (part.loaded) {
        msg += 'Loaded.<br/>';
      } else if (part.requested) {
        msg += 'Loading now...<br/>';
      } else {
        msg += 'Not needed yet.<br/>';
      }
    });
    statusDisplay.innerHTML = msg;
  }

  // Helper function to mark a part as requested, and process it into the dataSource.
  function processPart(part) {
    part.requested = true;
    updateStatusDisplay();
    dataSource.process(czmlPath + part.url).then(function () {
      loadingOverlay.style.display = 'none';
      part.loaded = true;
      updateStatusDisplay();

      // Follow the vehicle with the camera.
      if (!viewer.trackedEntity) {
        // 小车模型，相机放在 移动的模型上，同步移动
        viewer.trackedEntity = vehicleEntity =
          dataSource.entities.getById('Vehicle');
      }
    });
  }

  // Load the first part up front.
  processPart(partsToLoad[0]);

  // Load a new section before the clock naturally gets there.
  // Note this can't predict when a user may fast-forward to it.
  const preloadTimeInSeconds = 10;

  viewer.clock.onTick.addEventListener(function (clock) {
    // This example uses time offsets from the start to identify which parts need loading.
    const timeOffset = Cesium.JulianDate.secondsDifference(
      clock.currentTime,
      clock.startTime
    );

    // Filter the list of parts to just the ones that need loading right now.
    // Then, process each part that needs loading.
    partsToLoad
      .filter(function (part) {
        return (
          !part.requested &&
          timeOffset >= part.range[0] - preloadTimeInSeconds &&
          timeOffset <= part.range[1]
        );
      })
      .forEach(function (part) {
        processPart(part);
      });

    if (vehicleEntity) {
      const fuel = vehicleEntity.properties.fuel_remaining.getValue(
        clock.currentTime
      );
      if (Cesium.defined(fuel)) {
        fuelDisplay.textContent = `Fuel: ${fuel.toFixed(2)} gal`;
      }
    }
  });

  // 重置
  resetButtonBtnId.addEventListener('click', () => {
    viewer.clock.currentTime = viewer.clock.startTime;
    viewer.clock.shouldAnimate = true;

    partsToLoad.forEach(function (part) {
      part.requested = false;
      part.loaded = false;
    });

    dataSource.entities.removeAll();
    processPart(partsToLoad[0]);
  });

  // Show the status display below the reset button.
  statusDisplay.style.background = 'rgba(42, 42, 42, 0.7)';
  statusDisplay.style.padding = '5px 10px';
  document.getElementById('toolbar').appendChild(statusDisplay);

  // Show a multi-part custom property being read from CZML.
  fuelDisplay.style.background = 'rgba(42, 42, 42, 0.7)';
  fuelDisplay.style.padding = '5px 10px';
  fuelDisplay.style.marginTop = '5px';
  document.getElementById('toolbar').appendChild(fuelDisplay);
});
</script>

<style scoped>
* {
  padding: 0;
  margin: 0;
}
#container {
  height: 90vh;
  width: 90vw;
}

.pWrapCls {
  position: relative;
}

.fullSize {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  border: none;
  width: 100%;
  height: 100%;
}

#loadingOverlay {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0.9;
  width: 100%;
  height: 100%;
}

#loadingOverlay h1 {
  text-align: center;
  position: relative;
  top: 50%;
  margin-top: -0.5em;
}

#toolbar {
  top: 0;
  margin: 5px;
  padding: 2px 5px;
  position: absolute;
}
#resetButtonBtnId {
  top: 0;
  left: 380px;
  color: red;
  margin: 5px;
  padding: 2px 5px;
  z-index: 999;
  position: absolute;
  cursor: pointer;
}

.infoPanel {
  background: #2a2a2acc;
  padding: 4px;
  border: 1px solid #444;
  border-radius: 4px;
}
</style>
